import requests as re
import csv
import time

with open("Cookie.txt", mode='r') as f:
    cookies = f.read()
url = 'https://m.ctrip.com/restapi/soa2/13444/json/getCommentCollapseList?_fxpcqlniredt=09031108213065801388'
headers = {
    "Cookie": cookies,
    "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 "
        "Safari/537.36 Edg/115.0.1901.188 "
}
ID_list = [10758165, 97645, 75595]
for i in ID_list:
    json_data = {
        "arg": {"channelType": 2, "collapseType": 0, "commentTagId": 0, "pageIndex": 0, "pageSize": 10, "poiId": 0,
                "sourceType": 1, "sortType": 3, "starType": 0},
        "head": {"cid": "09031108213065801388", "ctok": "", "cver": "1.0", "lang": "01", "sid": "8888", "syscode": "09",
                 "auth": "", "xsid": "", "extension": []}}
    json_data['arg']['poiId'] = i
    for j in range(1, 301):
        json_data['arg']['pageIndex'] = j
        html = re.post(url, json=json_data, headers=headers).json()
        for k in range(10):
            if html['result']['items'][k]['userInfo'] != None:
                name = html['result']['items'][k]['userInfo']['userNick']
            else:
                name = None
            content = html['result']['items'][k]['content']
            time1 = html['result']['items'][k]['publishTypeTag']
            location = html['result']['items'][k]['ipLocatedName']
            print(name, content, time1, location)
            with open("景点评论.csv", mode='a', encoding="utf-8", newline='') as f:
                writer_csv = csv.writer(f)
                writer_csv.writerow([name, content, time1, location])
        time.sleep(0.5)
time.sleep(0.5)
